const { Router } = require('express')

const { Article } = require('../model/Article')
const { Comment } = require('../model/Comment')

const sexpage = require('mongoose-sex-page')

const router = Router()

router.get('/', async (req, res) => {
  const { page = 1 } = req.query
  const result = await sexpage(Article)
    .page(page)
    .size(5)
    .display(5)
    .find()
    .populate('author')
    .exec()
  res.render('home/index', result)
})

router.get('/article/:id', async (req, res) => {
  const { id } = req.params
  const article = await Article.findOne({ _id: id }).populate('author')

  const comments = await Comment.find({ article: id }).populate('user')

  res.render('home/article', { article, comments: comments.reverse() })
})

router.post('/artile/:aid/comment', async (req, res) => {
  const { aid } = req.params
  const { uid, content } = req.body

  await Comment.create({
    article: aid,
    user: uid,
    content
  })

  res.redirect(`/home/article/${aid}`)
})

module.exports = { router }
